﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using PortalWeb.CMS.Core.Entity;
using PortalWeb.CMS.Core.IManager;
using PortalWeb.Models.Cms;

namespace PortalWeb.Areas.CmsAdmin.Controllers
{
    [Authorize]
    public class CategoryController : Controller
    {
        public ICategoryManager CategoryManager { get; }
     
        public CategoryController(ICategoryManager categoryManager)
        {
            CategoryManager = categoryManager;
        }


        // GET: /Admin/News/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Admin/News/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [ValidateInput(false)]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Category category)
        {
            if (ModelState.IsValid)
            {
                category.ParentPath = category.ParentId.ToString();

                //设置固定值
                category = CategoryManager.Add(category);
                if (category.Id > 0)
                {
                    return View("AddSucess", new CategoryViewModel(category));
                }
            }
            return View(new CategoryViewModel(category));
        }

        /// <summary>
        /// 全部栏目
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string model)
        {
            ViewData["Model"] = model;
            return View();
        }

        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Category category = CategoryManager.Get(id);
            if (category == null)
            {
                return HttpNotFound();
            }
            return View(new CategoryViewModel(category));
        }

        public ActionResult Delete(int? id)
        {
            var article = CategoryManager.Get(id);
            if (article == null) return Json(false);

            //删除栏目
            if (CategoryManager.Delete(article))
            {
                return Json(true);
            }
            else return Json(false);
        }

        /// <summary>
        /// 文章列表Json【注意权限问题，普通人员是否可以访问？】
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="model"></param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录</param>
        /// <returns></returns>
        public async Task<ActionResult> JsonList(string title, string model, int pageIndex = 1, int pageSize = 20)
        {
            int offset = pageSize*(pageIndex - 1);
            int limint = pageSize*pageIndex;
            var data = await CategoryManager.LoadPageEntitiesAsync(p => p.Model == model, false, p => p.Id, offset, limint);
            var rows = data.Select(
                category => new CategoryViewModel
                {
                    Id = category.Id,
                    ParentId = category.ParentId,
                    Name = category.Name,
                    Model = category.Model
                });
            return Json(new {total = CategoryManager.Count(), rows = rows.ToList()});
        }

        //
        // GET: /Admin/Category/
        public ActionResult JsonTree(string model)
        {
            return Json(EasyuiTreeData(model), JsonRequestBehavior.AllowGet);
        }

        public async Task<List<EasyuiTreeNodeViewModel>> EasyuiTreeData(string model)
        {
            //栏目ID列表
            Dictionary<string, int> categoryIdList = new Dictionary<string, int>();
            //查询栏目列表
            var data = await CategoryManager.LoadAllEntitiesnAsync();
            IEnumerable<Category> categoryList = data.OrderBy(c => c.Order);
            if (!string.IsNullOrEmpty(model))
            {
                categoryList = categoryList.Where(c => c.Model == model);
            }
            //栏目parentParth
            var partentParthList = categoryList.Select(c => c.ParentPath).ToList();
            //遍历partentParth
            foreach (var partentParth in partentParthList)
            {
                //将partentParth分割为ID字符串列表
                var strCategoryIdList = partentParth.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
                //将CategoryID循环添加到栏目ID列表
                foreach (var strCategoryId in strCategoryIdList)
                {
                    if (!categoryIdList.ContainsKey(strCategoryId))
                        categoryIdList.Add(strCategoryId, int.Parse(strCategoryId));
                }
            }
            //栏目树
            var tree = new List<EasyuiTreeNodeViewModel>();
            //树栏目列表
            var data2 = await CategoryManager.LoadEntitiesAsync(c => categoryIdList.Values.Contains(c.ParentId));
            var categoryTreeList = data2.OrderByDescending(p => p.ParentPath).ThenBy(c => c.Order);
            //遍历树栏目列表
            foreach (var categoryTree in categoryTreeList)
            {
                //树中节点父栏目为当前栏目
                if (tree.Exists(n => n.parentid == categoryTree.Id))
                {
                    var children = tree.Where(n => n.parentid == categoryTree.Id).ToList();
                    tree.RemoveAll(n => n.parentid == categoryTree.Id);
                    tree.Add(new EasyuiTreeNodeViewModel()
                    {
                        id = categoryTree.Id,
                        parentid = categoryTree.ParentId,
                        text = categoryTree.Name,
                        children = children
                    });
                }
                else
                    tree.Add(new EasyuiTreeNodeViewModel()
                    {
                        id = categoryTree.Id,
                        parentid = categoryTree.ParentId,
                        text = categoryTree.Name
                    });
            }
            return tree;
        }
    }
}
